package cn.changeforyou.ide.idea.plugin.utils;

import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.impl.source.PsiPlainTextFileImpl;

/**
 * @author zhyu
 * @date 2020/8/3 16:32
 */
public class PsiFileUtil {

    public static PsiDirectory getSubParent(PsiFile psiFile, int count) {
        if(null == psiFile) {
            return null;
        }
        PsiDirectory parent = psiFile.getParent();
        for (int i = 1; i < count; i++) {
            parent = parent.getParent();
            if(null == parent) {
                return null;
            }
        }
        return parent;
    }


    /**
     * 自下而上寻找iml文件
     * @param project
     * @param parent
     * @return
     */
    public static  PsiPlainTextFileImpl findImlFromButtonToTop(Project project, PsiDirectory parent) {
        while(true) {
            if (parent.getVirtualFile().getPath().equals(project.getBasePath())) {
                break;
            }
            PsiElement[] children = parent.getChildren();
            if (children.length > 1) {
                for (PsiElement child : children) {
                    if(child instanceof PsiPlainTextFileImpl) {
                        PsiPlainTextFileImpl textFile = (PsiPlainTextFileImpl) child;
                        if (textFile.getName().endsWith(".iml")) {
                            return textFile;
                        }
                    }
                }
            }
            parent = parent.getParent();
        }
        return null;
    }
}
